<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */


class TeamAction extends HomeAction
{

    protected $Team;
    protected $TeamUser;

	function _initialize()
	{
		parent::_initialize();
		
		$this->Team = D('Team');
		$this->TeamUser = D('TeamUser');
		
		$topTeamUsers = $this->Team->getTopTeamUsers($_GET['tid']);
		$this->assign('topTeamUsers', $topTeamUsers);
	}


    //团队列表
    public function index()
    {
    	
		import('ORG.Util.Page');
    	$Category = D('Category');
    	
    	$cateID  = isset($_REQUEST['cid']) ? intval($_REQUEST['cid']) : 0;
    	$keyword = isset($_REQUEST['keyword']) ? trim($_REQUEST['keyword']) : '';
    	
    	$categories = F('cache_categories');
    	$category = $seo = $map = array();

    	if ($cateID && !isset($categories[$cateID]))
    	{
    		$this->error(L('category_not_existed'));
    	}

    	if ($cateID)
    	{
    		$category = $categories[$cateID];
    		$seo = array(
	    		'title' => $category['name'],
	    		'keywords' => $category['keywords'],
	    		'description' => $category['description'],
	    	);
    	}

    	$isUltimate = is_ultimate_category($cateID);
    	$map['parent'] = $isUltimate ? $category['parent'] : $cateID;
    	$order = array(
    		'display_order' => 'asc', 
    		'name' => 'asc',
    	);
    	$subCategories = $Category->where($map)->order($order)->select();
    	$breadCrumbs = get_category_path($cateID);

    	$map = $order = array();
    	$cateIDs = $parameter = '';

    	/*-------------------- 附加条件 ---------------------*/
    	$map['status'] = 1;
    	if ($cateID)
    	{
    		$cateIDs = get_sub_category_ids($cateID, 1);
    		$map['category_id'] = array('in', $cateIDs);
    		$parameter .= '&cid='.$cateID;
    	}
    	if (!empty($keyword))
    	{
    		$map['name'] = array('like', '%'.$keyword.'%');
    	}

    	$pageSize = $this->_global['teams_per_page'];

    	$total = $this->Team->where($map)->count();
    	$Page  = new Page($total, $pageSize);
		$Page->parameter = $parameter;
		$pagination = $Page->show();
    	$teams = $this->Team->where($map)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();
    	
    	//我加入的团队
    	$myTeams = array();
    	if (!empty($this->_user['user_id']))
    	{
	    	$TeamUser = D('TeamUser');
	    	$myTeams = $TeamUser->getUserTeams($this->_user['user_id']);
    	}

        $this->assign('seo', $seo);
    	$this->assign('cateID', $cateID);
    	$this->assign('keyword', $keyword);
    	$this->assign('sort', $sort);
    	$this->assign('breadCrumbs', $breadCrumbs);
    	$this->assign('category', $category);
    	$this->assign('subCategories', $subCategories);
    	$this->assign('teams', $teams);
    	$this->assign('myTeams', $myTeams);
    	$this->assign('pagination', $pagination);

    	$this->display();
    }
    
    
    //团队首页
    public function activity()
    {
    	
    	$Tag = D('Tag');
    	
    	$team = array();
    	$teamID = intval($_GET['tid']);
    	$team = $this->Team->find($teamID);
    	if (empty($team))
    	{
    		$this->error(L('team_not_existed'));
    	}
    	
    	$map = array('tag_id' => array('in', $team['tags']));
    	$team['tags'] = $Tag->where($map)->select();
    	
		//已回答问题
    	$View = D('QuestionAnswerView');
    	$limit = 5;
    	$map = $order = array();
    	$map['Answer.team_id'] = $teamID;
    	$order['Question.question_id'] = 'desc';
    	$questions = $View->where($map)->order($order)->limit($limit)->select();
    	
    	$this->assign('team', $team);
    	$this->assign('questions', $questions);
    	$this->display();
    }
    
    
    //团队问答
    public function qa()
    {
		
		import('ORG.Util.Page');    		
    	$View = D('QuestionAnswerView');
    	
    	$teamID = intval($_GET['tid']);
    	$team = $this->Team->find($teamID);
    	if (empty($team))
    	{
    		$this->error(L('team_not_existed'));
    	}
    	
    	$types  = array('all', 'recent', 'best', 'teamwork');
    	$type   = in_array($_GET['type'], $types) ? $_GET['type'] : 'all';
    	
		$parameter  = '';
		$parameter .= '&tid='.$teamID;
		$parameter .= '&type='.$type;

		$map = $order = array();
    	$map['Answer.team_id'] = $teamID;
    	$order['Question.question_id'] = 'desc';
    	$group = 'Question.question_id';
    	
    	switch ($type)
    	{
    		case 'recent':
    			$map['Question.status'] = 1;
    			break;
    		case 'best':
    			$map['Answer.is_best'] = 1;
    			break;
    		case 'teamwork':
    			$map['Answer.editor_count'] = array('gt', 0);
    			break;
    	}
    	
		$pageSize = 10;
		$total = $View->where($map)->count('DISTINCT Question.question_id');
		$Page  = new Page($total, $pageSize);
		$Page->parameter = $parameter;
		$pagination = $Page->show();
		
		$questions = $View->where($map)->order($order)->group($group)->limit($Page->firstRow.','.$Page->listRows)->select();
		
    	$this->assign('type', $type);
    	$this->assign('team', $team);
		$this->assign('pagination', $pagination);
    	$this->assign('questions', $questions);
    	$this->display();

    }
    
    
    //团队成员列表
    public function userlist()
    {
    	
    	import('ORG.Util.Page');		
		$View = D('TeamUserView');
		
    	$teamID = intval($_GET['tid']);
    	$team = $this->Team->find($teamID);
    	if (empty($team))
    	{
    		$this->error(L('team_not_existed'));
    	}
    	
	    $allowRemove = $team['leader_id'] == $this->_user['user_id'];
		
		$parameter = '';
		$map = array('TeamUser.team_id' => $teamID);
		$order = array('create_time' => 'desc');
		
		$pageSize = 30;
		$total = $View->where($map)->count();
		$Page  = new Page($total, $pageSize);
		$Page->parameter = $parameter;
		$pagination = $Page->show();
		$teamUsers = $View->where($map)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();

    	$this->assign('team', $team);
    	$this->assign('allowRemove', $allowRemove);
		$this->assign('pagination', $pagination);
		$this->assign('teamUsers', $teamUsers);
    	$this->display();
    }
    
    
    //团队设置
    public function setting()
    {
    	
    	$teamID = intval($_REQUEST['tid']);
    	$team = $this->Team->find($teamID);
    	if (empty($team))
    	{
    		$this->error(L('team_not_existed')); 		
    	}
    	
    	if ($this->_user['user_id'] != $team['leader_id'])
    	{
    		$this->error(L('no_perms_action'));
    	}
    	
    	$types = array('profile', 'userModeration');
    	$type = in_array($_GET['type'], $types) ? $_GET['type'] : 'userModeration';
    	
    	switch ($type)
    	{
    		case 'profile':
    			
    			$Tag = D('Tag');
    			$map = array('tag_id' => array('in', $team['tags']));
	    		$results = $Tag->where($map)->select();
	    		if (!empty($results))
	    		{
	    			foreach ($results as $tag)
		    		{
		    			$tags[] = $tag['name'];
		    		}
		    		$team['tags'] = implode(', ', $tags);	
	    		}
	    		
	    		L('team_tags_explain', sprintf(L('team_tags_explain'), $this->_global['max_team_tags']));
	    		$team['category_path'] = get_category_path($team['category_id']);
	    		
    			break;
    			
    		case 'userModeration':
    			
		    	import('ORG.Util.Page');		
				$View = D('TeamUserView');
		    	
				$statusArray = array(0, 1, -1);
		    	$status = in_array($_GET['status'], $statusArray) ? intval($_GET['status']) : 0;
		    	
				$parameter = '';
				$map = array(
					'TeamUser.team_id' => $team['team_id'], 
					'TeamUser.status' => $status,
				);
				$order = array('TeamUser.create_time' => 'desc');
				
				$parameter .= '&type='. $type;
				$parameter .= '&status'. $status;
				
				$pageSize = 10;
				$total = $View->where($map)->count();
				$Page  = new Page($total, $pageSize);
				$Page->parameter = $parameter;
				$pagination = $Page->show();
				$users = $View->where($map)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();

		    	$this->assign('status', $status);
		    	$this->assign('pagination', $pagination);
		    	$this->assign('users', $users);
		    	
				break;	
    	}
    	
    	$this->assign('type', $type);
    	$this->assign('team', $team);
    	$this->display();
    }
    
    
    //申请创建团队
    public function apply()
    {
    	
    	if (!$this->_userGroup['allow_create_team'])
    	{
    		$this->error(L('no_perms_action'));	
    	}
    	
    	$teamCreateLimit = $this->_global['max_creatable_team']; //允许创建的最大团队数
    	$myCreatedTeams = $this->Team->getUserTeamCount($this->_user['user_id']);
    	if ($myCreatedTeams >= $teamCreateLimit)
    	{
    		$this->error(L('exceed_team_create_limit'));
    	}
    	
    	if ($this->isPost())
    	{
    		if (empty($_POST['category_id']))
    		{
    			$this->error(L('category_required'));
    		}
	
    		$data = array(
	    		'name' 		  => $_POST['name'],
	    		'category_id' => intval($_POST['category_id']),
	    		'leader_id'   => $this->_user['user_id'],
	    		'leader_name' => $this->_user['username'],
	    		'about'       => trim($_POST['about']),
	    		'status'      => 0,
	    		'allow_join'  => 1,
	    		'create_time' => time(),
	    	);
	    	
	    	$teamID  = $this->Team->add($data);
	    	$message = L('team_require_approval');
	    	$jumpUrl = format_team_url($teamID, $data['name']);
	    	
	    	$this->assign('jumpUrl', $jumpUrl);
	    	$this->success($message);	
    	}
    	else 
    	{
    		$this->display();	
    	}
    }
    
    
    //编辑团队信息
    public function profile()
    {
    	
    	$Tag = D('Tag');
    	
    	$teamID = intval($_REQUEST['tid']);
    	$team = $this->Team->find($teamID);
    	if (empty($team))
    	{
    		$this->error(L('team_not_existed'));
    	}
    	
    	if ($this->_user['user_id'] != $team['leader_id'])
    	{
    		$this->error(L('no_perms_action'));
    	}
	
		$teamData = $tagData = $tagIDs = array();
		
		if (!empty($_POST['recategorize']) && empty($_POST['category_id']))
		{
			$this->error(L('category_required'));
		}
		
		if (!empty($_FILES['logo']))
		{
			
		}
				
		$tags = explode(',', $_POST['tags']);
		foreach ($tags as $tag)
		{
			$tag = trim($tag);
			$result = $Tag->getTagByName($tag);
			if (empty($result))
			 {
			 	$tagData = array(
			 		'name' => $tag, 
			 		'create_time' => time(), 
			 		'status' => 1,
			 	);
			 	if (strlen($tag) >= 3)
			 	{
			 		$tagIDs[] = $Tag->add($tagData);	
			 	}
			 }
			 else 
			 {
			 	$tagIDs[] = $result['tag_id']; 
			 }
		}
		
		$tags = implode(',', array_slice($tagIDs, 0, 5));
		$teamData['tags'] = $tags;
		$teamData['about'] = trim($_POST['about']);
		$teamData['allow_join'] = intval($_POST['allow_join']);
		$teamData['new_teammate_alert'] = intval($_POST['new_teammate_alert']);
		
		$name = trim($_POST['name']);
		if ($this->_global['allow_team_rename'] && !empty($name))
		{
			$teamData['name'] = $name;
		}
		
		if ($this->_global['allow_team_recategorize'] && !empty($_POST['category_id']))
		{
			$teamData['category_id'] = intval($_POST['category_id']);
		}
		
		$where = array('team_id' => $teamID);
		$this->Team->where($where)->save($teamData);
		
		$this->success(L('team_profile_edited'));
    }
    
    
        //团员管理
    public function userModeration()
    {
    	
    	$teamID = intval($_POST['tid']);
    	$team = $this->Team->find($teamID);
    	if (empty($team) || $this->_user['user_id'] != $team['leader_id'])
    	{
    		$this->error(L('no_perms_action'));
    	}
    	
    	if (!empty($_POST['mods']))
    	{
    		if (isset($_POST['approve']))
    		{
    			$status = 1;
    			$message = L('team_user_approved');
    		}
    		elseif (isset($_POST['disapprove']))
    		{
    			$status = -1;
    			$message = L('team_user_disapproved');
    		}
    		
    		foreach ($_POST['mods'] as $mod)
    		{
    			$where = array('team_id' => $teamID, 'user_id' => $mod);
    			$this->TeamUser->where($where)->setField('status', $status);
    		}
    		
    		$this->Team->updateUserCount($teamID);
    		$this->success($message);
    	}
    	else 
    	{
    		$this->redirect('Team/setting', array('tid' => $teamID, 'type' => 'userModeration'));
    	}
    }
    
    
    //申请加入团队
    public function joinTeam()
    {
    	
    	$teamID = intval($_GET['tid']);
    	$map = array(
    		'team_id' => $teamID,
    		'status' => 1,	
    	);
    	$team = $this->Team->where($map)->find();
    	if (empty($team))
    	{
    		$this->error(L('team_not_existed'));
    	}
    	
    	if (!$team['allow_join'])
    	{
    		$this->error(L('team_refuse_join'));
    	}
    	
    	//团队人数检查
    	$teamGroup = F('cache_team_group_'. $team['group_id']);
    	if ($team['user_count'] >= $teamGroup['max_user'])
    	{
    		$this->error(L('team_is_full'));
    	}
    	
    	$map = array(
    		'team_id' => $teamID,
    		'user_id' => $this->_user['user_id'],	
    	);
    	$result = $this->TeamUser->where($map)->find();
    	$interval = 7 * 86400; //申请时间间隔
    	switch (intval($result['status']))
    	{
    		case -1:
    			if ($result['create_time'] + $interval < time())
    			{
    				$message = sprintf(L('team_apply_disapproved'), format_date($result['create_time'] + $interval));
    				$this->error($message);
    			}    			
    			break;
    		case 0:
    			$this->error(L('team_apply_in_processing'));	
    			break;
    		case 1:
    			$this->error(L('team_joined_already'));
 				break;
    	}
    	
    	$data = array(
    		'team_id' => $teamID,
    		'user_id' => $this->_user['user_id'],
    		'create_time' => time(),
    		'status' => 0,
    	);
    	$userID = $this->TeamUser->replace($data);
    	
    	//发送新入团申请通知
    	import('ORG.Util.Http');
    	$requestUrl = U('Notification/newTeammateAlert', array('uid'=>$userID,'tid'=>$teamID));
    	Http::async_request($requestUrl);
    	
    	$this->success('join_team_require_aproval');
    }
    
    
    //退出团队
    public function quitTeam()
    {
    	
    	$teamID = intval($_GET['tid']);
    	$isTeamUser = $this->UserTeam->isTeamUser($teamID, $this->_user['user_id']);
    	if (!$isTeamUser)
    	{
    		$this->error(L('no_perms_action'));
    	}
    	
    	//删除所在团队记录
		$this->TeamUser->deleteUser($teamID, $userID);
		
		//更新团队成员数
    	$this->Team->updateUserCount($teamID);
    }
    
    
    //解散团队
    public function disbandTeam()
    {
    	$teamID = intval($_REQUEST['tid']);
    	$team = $this->Team->find($teamID);
    	if (empty($team) || $this->_user['user_id'] != $team['leader_id'])
    	{
    		$this->error(L('no_perms_action'));
    	}
    	
    	if (isset($_POST['cancel']))
    	{
    		$this->redirect('Team/setting', array('tid' => $teamID));
    	}
    	
    	if (!isset($_POST['confirm']))
    	{
    		$this->assign('action', U('Team/disbandTeam', array('tid' => $teamID)));
    		$this->confirm(L('team_disband_confirm'));
    	}
    	else 
    	{
    		//disband team
    	}
    }

}


/* End of file TagAction.class.php */
/* Location: ./App/Lib/Action/Home/TagAction.class.php */